export default function Segment(startPoint, endPoint) {
    this.startPoint = startPoint;
    this.endPoint = endPoint;
    this.range = 10;
}

Segment.prototype.draw = function (context, state) {
    context.save();

    context.beginPath();
    context.lineWidth = 4;
    context.strokeStyle = state.isSelectd? 'red' : state.color;
    context.moveTo(this.startPoint.x, this.startPoint.y);
    context.lineTo(this.endPoint.x, this.endPoint.y);
    context.stroke();

    context.restore();
};

Segment.prototype.contains = function (p) {
    var p1 = this.startPoint;
    var p2 = this.endPoint;

    var cross = (p2.x - p1.x) * (p.x - p1.x) + (p2.y - p1.y) * (p.y - p1.y);

    if (cross <= 0) {
        return false;
    }

    var d2 = (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y);

    if (cross >= d2) {
        return false;
    }

    var r = cross / d2;
    var px = p1.x + (p2.x - p1.x) * r;
    var py = p1.y + (p2.y - p1.y) * r;

    return Math.sqrt((p.x - px) * (p.x - px) + (py - p.y) * (py - p.y)) <= this.range;
};